﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MySql.Data.MySqlClient;
using System.Web.Security;

namespace TKWeb.Passport
{
	public partial class Register : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{

		}

		public static bool IsEmail(string str_Email)
		{
			return System.Text.RegularExpressions.Regex.IsMatch(str_Email, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
		}

		protected void Button1_Click(object sender, EventArgs e)
		{
			tbEmail.Text = tbEmail.Text.Trim();
			tbPwd.Text = tbPwd.Text.Trim();
			tbRePwd.Text = tbRePwd.Text.Trim();
			if(string.IsNullOrEmpty(tbEmail.Text) || string.IsNullOrEmpty(tbPwd.Text))
			{
				lbError.Visible = true;
				lbError.Text = "请输入Email或密码！";
				return;
			}

			if (tbEmail.Text.Length > 50)
			{
				lbError.Visible = true;
				lbError.Text = "Email过长！";
				return;
			}

			if (!(tbPwd.Text.Length >= 6 && tbPwd.Text.Length <= 16))
			{
				lbError.Visible = true;
				lbError.Text = "密码长度不在指定范围！";
				return;
			}

			if (!IsEmail(tbEmail.Text))
			{
				lbError.Visible = true;
				lbError.Text = "Email格式错误！";
				return;
			}

			if (tbPwd.Text != tbRePwd.Text)
			{
				lbError.Visible = true;
				lbError.Text = "两次输入密码不一致！";
				return;
			}

			if(CheckEmail(tbEmail.Text))
			{
				lbError.Visible = true;
				lbError.Text = "该Email已经被注册！";
				return;
			}

			System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
			string md5Pwd =  FormsAuthentication.HashPasswordForStoringInConfigFile(string.Format("abc{0}abc", tbPwd.Text), "MD5");
			int userId = (int)Global.DBAccess.InsertData("insert into user_info(email,pwd,created,logined) values(@email,@pwd,sysdate(),sysdate())",new MySqlParameter[]{ new MySqlParameter("email", tbEmail.Text), new MySqlParameter("pwd", md5Pwd)});
			this.Session["UserId"] = userId;
			Response.Redirect("/Portal/JobConfig.aspx");
		}

		private bool CheckEmail(string email)
		{
			return Global.DBAccess.GetCount("select count(*) from user_info where email=@email", new MySqlParameter("email", email)) > 0;
		}
	}
}